package com.neuedu.springmvc.convert;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 将String类型参数，转换成  java.util.Date
 */
public class String2DateConverter implements Converter<String, Date> {

    static List<SimpleDateFormat> sdfs = new ArrayList();

    /**
     * 2022-12-04
     * 2022/12/04 10:01:05
     * 12/04/2022 10:01:05
     */
    static{
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd"));
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd"));
    }


    @Override
    public Date convert(String s) {
        Date date = null;

        for (SimpleDateFormat sdf : sdfs) {
            try {
                date = sdf.parse(s);
                return date;

            } catch ( ParseException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}